package file

import (
	// "exec"
	// "file/filepath"
	"fmt"
	// "io"
	"io/ioutil"
	"os"
	"strings"
)

type Folder struct {
	Name string
	Path string
}

type File struct {
	Encoding string
	Name     string
	Path     string
	Code     map[string]StringCodings
}

// type Files struct {
// 	Name  string
// 	Files map[int]File
// }

type Filer interface {
	// Dir(string) Folder
	// Write(string) (int, error)
	// Read(string) (int, error)
}

func GetDir(path string, folders *[]Folder) {

	list, err := ioutil.ReadDir(path)
	if err != nil {
		return
	}

	path = strings.Replace(path, "\\", "/", -1) //n是要替换的次数，n=-1意思是没有限制，全部替换
	pathfield := strings.SplitAfter(path, "/")
	pathsize := len(pathfield)
	var fdr Folder
	fdr.Path = path
	if pathsize-1 >= 0 {
		fdr.Name = pathfield[pathsize-1]
	}

	*folders = append(*folders, fdr)

	fmt.Println("正在检测目录...", fdr.Name)
	for _, v := range list {
		if v.IsDir() {

			GetDir(path+"/"+v.Name(), folders)

		}
	}
	fmt.Println("目录检测完毕...", fdr.Name)
	return
}

func GetFile(path string, files *[]File) {
	list, err := ioutil.ReadDir(path)
	if err != nil {
		return
	}
	fmt.Println("检测文件...", path)
	for _, v := range list {
		if !v.IsDir() {

			var file File
			file.Name = v.Name()
			file.Path = path
			file.GetFileStringCodings("CRC32")
			// file.GetFileStringCodings("MD5")

			*files = append(*files, file)

		}
	}

}

func Write(dat string) (int, error) {
	path := "D:/FilterTest/"

	err := os.MkdirAll(path, 0777)
	if err != nil {
		return 0, err
	}
	filename := "test.json"

	return write(path+filename, dat)
}

func write(namepath string, dat string) (int, error) {
	file, err := os.OpenFile(namepath, os.O_RDWR|os.O_EXCL, 0777)
	if os.IsNotExist(err) {
		file, err = os.OpenFile(namepath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0777)
	}
	defer file.Close()
	if err != nil {
		return 0, err
	}

	return file.Write([]byte(dat))
}
